<template>
  <div class="container">
    <div class="video-wrapper">
      <video-player
        class="video-player vjs-custom-skin"
        ref="videoPlayer"
        :playsinline="true"
        :options="playerOptions"
        @play="onPlayerPlay($event)"
        @pause="onPlayerPause($event)"
        @loadeddata="onPlayerLoadeddata($event)"
        @ended="onPlayerEnded($event)"
        @timeupdate="onPlayerTimeupdate($event)"
        @canplay="onPlayerCanplay($event)">
      </video-player>
    </div>
    <div class="video-infos">
      <div class="video-title"><span>课程详情：</span>{{subject.kcname}}</div>
      <div class="video-date">{{subject.createtime | timeFormat('yyyy-mm-dd')}}</div>
    </div>
  </div>
</template>

<script>
  import util from '@/common/util';
  export default {
    data () {
      return {
        mobile: '',
        isPlayed: false,
        subject: '',
        isDrag: false,
        paused: true,
        kc_id: '', //课程id
        idcard: '', //学员身份证
        aDuration: 0, //视频总时长
        currentTime: 0, //视频播放时间
        timer: '',
        playerOptions : {
          playbackRates: [], //播放速度
          autoplay: true, //如果true,浏览器准备好时开始回放。
          muted: false, // 默认情况下将会消除任何音频。
          loop: false, // 导致视频一结束就重新开始。
          preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
          language: 'zh-CN',
          aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
          fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
          sources: [{
            type: "video/mp4",//这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: "" //url地址
          }],
          poster: "http://218.22.139.29:5555/public/static/img/mock.jpg", //你的封面地址
          // width: document.documentElement.clientWidth, //播放器宽度
          notSupportedMessage: '此视频暂无法播放，请稍后再试', //允许覆盖Video.js无法播放媒体源时显示的默认信息。
          controlBar: {
            timeDivider: true,
            durationDisplay: true,
            remainingTimeDisplay: false,
            fullscreenToggle: true  //全屏按钮
          }
        }
      }
    },
    created() {
      let that = this;
      console.log(navigator.appVersion)
      that.mobile =navigator.appVersion.indexOf("iPhone") !== -1 ? "iPhone" : "android";
      that.kc_id = that.$route.query.id;
      that.idcard = util.storage.get('userinfo').idcard;
      that.getVideo(); //调用获取课程详情
      console.log('idcard:',that.idcard)
    },
    mounted() {
      // 存储视频播放进度
       this.putLearningObj();
    },
    destroyed () {
      // 如果定时器在运行则关闭
      if (this.timer) {
        clearTimeout(this.timer)
      }
    },
    computed: {
      player() {
        return this.$refs.videoPlayer.player
      }
    },
    methods: {
      getVideo() { //获取课程详情
        let that = this;
        that.$api.post('/mobile/Index/index_detail',{'user':{'id':that.kc_id,'idcard':that.idcard}}, r => {
          console.log('课程详情：',r);
          that.subject = r.data.subject;
          that.playerOptions.sources[0].src = util.baseURL + r.data.subject.link;
         console.log('是否有score',!!r.data.score)
          if(!!r.data.score){
            that.currentTime = Math.ceil(r.data.score.gksc);
            console.log('score中观看时长：',that.currentTime);
          }
        })
      },
      putLearningObj () { // 保存播放进度方法
        let that = this;
        that.timer = setTimeout(function(){
          console.log('保存的播放进度：',that.currentTime)
          let learningDuration = {  //学员学习信息
            kc_id: that.kc_id,
            aDuration: that.aDuration,
            currentTime: that.currentTime,
            idcard: that.idcard
          };
          console.log('视频暂停了吗', that.paused)
          if (!that.paused) {
            that.$api.post('/mobile/Index/setcur', {'user':learningDuration}, r => {
              console.log('保存视频：',r)
            });
          }
          that.putLearningObj ()
        },10000)
      },
      // 播放视频
      onPlayerPlay(player) {
        this.paused = false;
      },

      // 暂停视频
      onPlayerPause(player) {
        let that = this;
        this.paused = true;
        this.currentTime = Math.ceil(player.cache_.currentTime);
        let learningDuration = {  //学员学习信息
          kc_id: that.kc_id,
          aDuration: that.aDuration,
          currentTime: that.currentTime,
          idcard: that.idcard
        };
        that.$api.post('/mobile/Index/setcur', {'user':learningDuration}, r => {
          console.log('暂停保存视频：',r)
        });
      },


      //监听媒体是否已到达结尾，播放完
      onPlayerEnded (player) {
        let that = this;
        console.log('playerend',player);
        this.isPlayed = true;
        this.currentTime = Math.ceil(player.cache_.currentTime);
        console.log('播放完后',this.currentTime)
        let learningDuration = {  //学员学习信息
          kc_id: that.kc_id,
          aDuration: that.aDuration,
          currentTime: that.currentTime,
          idcard: that.idcard
        };
        that.$api.post('/mobile/Index/setcur', {'user':learningDuration}, r => {
          console.log('结束保存视频：',r)
        });
      },

      //当播放器在当前播放位置下载数据时触发
      onPlayerLoadeddata (player) {
        // console.log(player);
        let that = this;
        console.log('Loadeddata当前',this.currentTime)
        if(that.currentTime !== 0){
          player.currentTime(that.currentTime);
        }
        that.aDuration = parseInt(player['cache_'].duration);
        console.log('总长：', that.aDuration);
        if(that.currentTime >= that.aDuration){  //判断视频是否播放完成过
          that.isPlayed = true;
        }
        console.log('视频播放完成',that.isPlayed)
      },

        // 当前播放位置发生变化时触发
      onPlayerTimeupdate (player) {
        let time = Math.ceil(player.cache_.currentTime);
        if((time - this.currentTime) > 1 && !this.isPlayed){
          player.currentTime(this.currentTime)
        } else {
          this.currentTime = Math.ceil(player.cache_.currentTime);
        }
      },

      onPlayerCanplay(player) {
        let that = this;
       // alert(that.currentTime);
        //console.log('当前',that.currentTime)
        if(that.mobile === 'iPhone'){
          console.log('这是苹果')
          player.currentTime(that.currentTime);
        }
      },
      //onPlayerCanplaythrough(player) { },

    }
  }
</script>

<style scoped>
 .video-infos {
   padding: 12px;
   line-height: 1.5;
   background-color: #fff;
  }
  .video-title {
    font-size: .32rem;
  }
  .video-date {
    font-size: .28rem;
  }
</style>
